<script setup lang="ts">
import type { ComponentExposed } from 'vue-component-type-helpers'
import { cloneDeep } from 'lodash-es'
import type {
  _IndicatorRule,
} from '../../index'
import { SettingPanel } from '../'
import type {
  AlarmSaveOrUpdateWarningRuleParamsItem,
} from '@/types'
import { alarmApi } from '@/api'
import type { STORAGE_MODES } from '@/enum/modules/indicator'
import { STORAGE_MODES_OPTIONS } from '@/mixins/StatisticalIndicators/MixinStatisticalIndicators'

defineOptions({ name: 'ParticlesSettingPanel' })

const props = defineProps<{
  indicatorInfo?: any
  particlesData: AlarmSaveOrUpdateWarningRuleParamsItem[]
}>()
// ------------------use------------------
// #region
const { $message } = useCurrentInstance()
const [data, setData] = useState<_IndicatorRule[]>([])
const [currentData, setCurrentData] = useState<
  _IndicatorRule[]
>([])
const [tabActive, setTabActive] = useState<STORAGE_MODES | null>(null)
// #endregion
// ------------------静态变量------------------
// #region

// #endregion
// ------------------动态变量------------------
// #region

// #endregion
// ------------------ref-----------
// #region
const monitorGroup = ref<STORAGE_MODES[]>([])
const settingPanelRef
  = ref<ComponentExposed<typeof SettingPanel>>()
// #endregion
// ------------------reactive------
// #region

// #endregion
// ------------------computed------
// #region
const MONITOR_TYPE = computed(() => {
  const tts = (props.indicatorInfo.indicatorDataStoreCoreList || [])
    .map((item: any) => item.timeType)
  return STORAGE_MODES_OPTIONS.filter(item => tts.includes(item.value))
})
const tabMonitorData = computed(() => {
  return unref(MONITOR_TYPE).filter(item =>
    monitorGroup.value.includes(item.value),
  )
})
// #endregion
// ------------------生命周期------------------
// #region

// #endregion
// ------------------内置方法---------------------
// #region
watch(
  () => props.particlesData,
  async () => {
    if (props.indicatorInfo.statisticalType !== 1) {
      tabActive.value = null
      return
    }
    setCurrentData([])
    monitorGroup.value = []
    const o = props.particlesData.filter(item => item.timeType).map(
      // item => item.monitorType,
      item => item.timeType,
    ) as STORAGE_MODES[]
    monitorGroup.value = o
    setData(props.particlesData)
    await nextTick()
    if (o.length === 0)
      return
    const newTab = o[0]!
    handleTabChange(newTab, false)
  },
  {
    immediate: true,
  },
)
// #endregion

// ------------------方法---------------------
// #region
async function handleCheckboxClick(i: STORAGE_MODES) {
  const isExistence = monitorGroup.value.includes(i)
  // console.log('点击', i, isExistence);
  let newTab = null
  if (isExistence) {
    const newMonitorGroup = [
      ...new Set(
        monitorGroup.value.filter(item => item !== i),
      ),
    ]
    if (newMonitorGroup.length === 0) {
      newTab = null
    }
    else {
      newTab = newMonitorGroup[0]!
    }
    monitorGroup.value = newMonitorGroup
    handleTabChange(newTab, false)
  }
  else {
    const valid = await settingPanelRef.value?.validate?.()
    if (!valid)
      return
    monitorGroup.value.push(i)
    newTab = i
    updateData(i, tabActive.value)
    handleTabChange(newTab)
  }
}
async function save() {
  const isValid = await settingPanelRef.value?.validate?.()
  if (!isValid && monitorGroup.value.length > 0)
    return
  updateData()
  await nextTick()
  const params = data.value
    .filter(item =>
      item.timeType && monitorGroup.value.includes(item.timeType),
    )
    .map(item => ({
      ...item,
      indicatorId: props.indicatorInfo.id,
      indicatorCode: props.indicatorInfo.indicatorCode,
      statisticalType: props.indicatorInfo.statisticalType,
    }))
  if (params.length === 0) {
    if (props.particlesData.length === 0) {
      $message.info('请先设置规则！')
      return false
    }
    else {
      // 解绑
      await alarmApi.deleteWarningRuleBatch([
        props.indicatorInfo.id,
      ])
      setCurrentData([])
      return true
    }
  }
  await alarmApi.saveOrUpdateWarningRule(params)
  return true
}
function updateData(
  newAct: any = tabActive.value,
  oldAct?: any,
) {
  const newData = settingPanelRef.value?.getData?.()
  const unchangedData = data.value.filter(
    item => item.timeType !== (oldAct ?? newAct),
  )
  setData([
    ...new Set(cloneDeep([...unchangedData, ...newData])),
  ])
}
async function handleTabChange(
  newAct: STORAGE_MODES | null,
  isValid = true,
) {
  if (props.indicatorInfo.statisticalType !== 1)
    return
  if (isValid) {
    // 切换之前进行验证
    const valid = await settingPanelRef.value?.validate?.()
    if (!valid)
      return
    // 验证通过
    // 更新数据
    updateData(newAct, tabActive.value)
  }

  // 设置展示值
  const o = data.value.filter(
    item => item.timeType === newAct,
  )
  setCurrentData(cloneDeep(o))
  await nextTick()
  settingPanelRef.value?.reset?.()
  setTabActive(newAct)
}
function reset() {
  settingPanelRef.value?.reset?.()
}
// #endregion
defineExpose({
  save,
  reset,
})
</script>

<template>
  <div class="particles-setting-panel">
    <div class="align-center checkbox-container flex">
      <span class="fs-14 flex-incompressible">
        监控颗粒度：
      </span>
      <el-checkbox-group :model-value="monitorGroup">
        <el-checkbox
          v-for="item in MONITOR_TYPE"
          :key="item.value"
          :value="item.value"
          @click="handleCheckboxClick(item.value)"
        >
          {{ item.label }}
        </el-checkbox>
      </el-checkbox-group>
    </div>
    <b-mask
      content="请先选择颗粒度"
      :show="monitorGroup.length === 0"
      class="margin-top-sm seeting-container flex gap-col-sm"
    >
      <div class="flex-incompressible list text-center">
        <li
          v-for="item in tabMonitorData"
          :key="item.value"
          class="fs-14 padding-lr-xs text-bold c-pointer align-center box-border flex"
          :class="[
            {
              active: tabActive === item.value,
            },
          ]"
          @click="handleTabChange(item.value)"
        >
          <span
            class="flex-fillRemaining text-overflow-hide"
          >
            {{ item.label }}
          </span>
        </li>
      </div>
      <SettingPanel
        ref="settingPanelRef"
        :data="currentData"
        :title="MONITOR_TYPE.find(v => v.value === tabActive)?.label"
        :monitor-type="tabActive"
        :time-type="tabActive"
        :unit="indicatorInfo.unitName"
        class="flex-fillRemaining !padding-0"
      />
    </b-mask>
  </div>
</template>

<style lang="scss" scoped>
//------------------组件样式------------------
.list {
  list-style-type: none;
  width: 100px;
  background: var(--el-color-primary);
  li {
    height: 40px;
    color: var(--el-bg-color);
  }
  li.active {
    color: var(--el-color-primary);
    background-color: var(--el-color-primary-light-9);
  }
}
.el-tabs {

  :deep(.el-tabs__item:not(.is-active)) {
    color: var(--el-bg-color);
  }
  :deep(.el-tabs__nav-scroll) {
    background-color: var(--el-color-primary);
  }

  :deep(.el-tabs__item.is-active) {
    // transition: background-color 0.3s;
    // transition-delay: 0.3s;
    font-weight: bold;
    background-color: var(--el-color-primary-light-9);
  }
}
.checkbox-container {
  & > span {
    color: var(--el-text-color-secondary);
  }
}
.seeting-container {
  width: 100%;
  height: 500px;
}
.particles-setting-panel {
  min-width: 600px;
}
//-------------样式穿透-------------
</style>
